<script>
const plugin = requirePlugin("WechatSI");
export default {
  name: "QuestionReader",
  props: {
    content: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      reading: false,
      touching: false,
      res: null,
      music: null,
    };
  },
  methods: {
    handleTouchStart() {
      this.touching = true;
    },
    handleTouchEnd() {
      this.touching = false;
    },
    bindClick() {
      if (this.reading) {
        this.stopAudio();
      } else {
        this.readQuestion();
      }
    },
    readQuestion() {
      this.reading = true;
      if (this.res !== null) {
        this.playAudio();
        return;
      }
      plugin.textToSpeech({
        lang: "zh_CN",
        tts: true,
        content: this.content,
        success: (res) => {
          // console.log("success tts", res);
          this.res = res;
          this.playAudio();
        },
        fail: (res) => {
          console.log("fail tts", res);
        },
      });
    },
    playAudio() {
      if (this.music === null) this.music = uni.createInnerAudioContext(); //创建播放器对象
      this.music.src = this.res.filename;
      this.music.play(); //执行播放
      this.music.onEnded(this.stopAudio);
    },
    stopAudio() {
      if (this.music === null) {
        console.error("music is null");
        return;
      }
      this.music.stop();
      this.reading = false;
    },
  },
  unmounted() {
    if (this.music) this.music.destroy();
  },
};
</script>

<template>
  <view @click="bindClick">
    <view v-if="reading">
      <slot name="active">
        <view class="flex-row justify-center box hover">
          <image class="image" src="/static/icon/sound-solid-pink.svg" />
        </view>
      </slot>
    </view>
    <view v-else>
      <slot name="inactive">
        <view class="flex-row justify-center box" hover-class="hover">
          <image class="image" src="/static/icon/sound-solid.svg" />
        </view>
      </slot>
    </view>
  </view>
</template>

<style scoped lang="css">
.image {
  width: 48rpx;
  height: 48rpx;
}

.box {
  padding: 8rpx;
  border-radius: 16rpx;
}

.hover {
  background-color: #ffeded;
}
</style>